package vn.com.pavibook.admin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import vn.com.pavibook.admin.service.ManageBookService;
import vn.com.pavibook.domain.model.Book;
import vn.com.pavibook.domain.model.PagingInfo;
import vn.com.pavibook.domain.model.SearchResult;
import vn.com.pavibook.model.vo.BookVO;
import vn.com.pavibook.utils.BookValidaton;

@Controller
public class ManageBookController{
	
	private static final int offset = 10;
	
	private static final Logger logger = LoggerFactory.getLogger(ManageBookController.class);
	
	@Autowired
	private ManageBookService manageBookService;
	
	@Autowired
	private BookValidaton bookValidaton;
	
	@RequestMapping(value = "/admin/book-info", method=RequestMethod.GET)
	public String openManageBook(Model model){
		//get username
		SecurityContext context = SecurityContextHolder.getContext();
		String username = context.getAuthentication().getName();
		
		PagingInfo pagingInfo = new PagingInfo(offset, 1);
		SearchResult<Book> result = manageBookService.getListBookByUsername(username, pagingInfo, null,null);
		List<Book> listBook = result.getSearchResult();
		PagingInfo pagingInfoNew = result.getPagingInfo();
		manageBookService.createNewBook(model, null);
		model.addAttribute("listBook", listBook);
		model.addAttribute("pagingInfo", pagingInfoNew);
		
		return "admin/thong-tin-sach";
	}
	
	@RequestMapping(value = "/admin/searchBook", method = RequestMethod.POST)
	public String searchPublisher(Model model, 
			@RequestParam("pageIndex") int pageIndex, @RequestParam("keyword") String keyword, @RequestParam("typeSearch") String typeSearch) {
		
		//get username
		SecurityContext context = SecurityContextHolder.getContext();
		String username = context.getAuthentication().getName();
		
		PagingInfo pagingInfo = new PagingInfo(offset, pageIndex);
		SearchResult<Book> result = new SearchResult<Book>();
		if(StringUtils.isEmpty(keyword) || StringUtils.isEmpty(typeSearch)){
			result = manageBookService.getListBookByUsername(username, pagingInfo, null,null);
		} else {
			result = manageBookService.getListBookByUsername(username, pagingInfo, keyword, typeSearch);
		}
		List<Book> listBook = result.getSearchResult();
		model.addAttribute("listBook", listBook);
		model.addAttribute("pagingInfo", pagingInfo);
		model.addAttribute("keyword", keyword);
		model.addAttribute("typeSearch", typeSearch);
		return "admin/thong-tin-sach";
	}
	
	//create add new
	@RequestMapping(value = "/admin/add-book", method=RequestMethod.GET)
	public String createAddNewBook(Model model){
		logger.debug("controller createAddNewBook");
		BookVO bookVO = new BookVO();
		model.addAttribute("bookVO", bookVO);
		
		manageBookService.createNewBook(model, bookVO);
		return "admin/add-books";
	}
	
	//save add new
	@RequestMapping(value = "/admin/save-book")
	public String saveBook(Model model, @ModelAttribute("bookVO") @Valid BookVO bookVO, BindingResult result,HttpServletRequest request){
		logger.debug("controller saveBook");
		if(result.hasErrors()){
			bookValidaton.validate(bookVO, result);
			manageBookService.createNewBook(model, bookVO);
			return "admin/add-books";
		}
		boolean isEdit = false;
		if(bookVO.getId() != 0){
			isEdit = true;
		}
		boolean upload = manageBookService.uploadFileBook(model, bookVO, request, isEdit);
		if(!upload){
			manageBookService.createNewBook(model, bookVO);
			return "admin/add-books";
		}else{
			manageBookService.saveBook(bookVO, isEdit);
		}
		return "redirect:book-info";
	}
	
	@RequestMapping(value="admin/ajax/viewDetailBook", method=RequestMethod.GET)
	public ModelAndView viewDetailPublisher(@RequestParam("id") int id){
		ModelAndView model = new ModelAndView("admin/view-detail-book");
		BookVO bookVO = manageBookService.getBookDetail(id);
		
		//get name publisher
		SecurityContext context = SecurityContextHolder.getContext();
		String username = context.getAuthentication().getName();
		String publisherName = manageBookService.getNamePublishByUsername(username);
		
		//get name book type
		String bookTypeName = manageBookService.getNameBookTypeById(bookVO.getBookTypeId());
		model.addObject("bookVO", bookVO);
		model.addObject("publisherName", publisherName);
		model.addObject("bookTypeName", bookTypeName);
		return model;
	}
	
	//edit
	@RequestMapping(value = "/admin/edit-book", method=RequestMethod.GET)
	public String editBook(Model model, @RequestParam("id") int id){
		logger.debug("controller edit book");
		BookVO bookVO = new BookVO();
		bookVO = manageBookService.getBookDetail(id);
		model.addAttribute("bookVO", bookVO);
		model = manageBookService.createNewBook(model, bookVO);
		model.addAttribute("bookTypeChoose", bookVO.getBookTypeId());
		model.addAttribute("numberRepublishChoose", bookVO.getNumberRepublish());
		return "admin/add-books";
	}
	
	//delete
	@RequestMapping(value = "/admin/delete-book", method=RequestMethod.GET)
	public String deleteBook(Model model, @RequestParam("bookId") int bookId){
		logger.debug("controller delete book");
		manageBookService.deleteBook(bookId);
		return "redirect:book-info";
	}
	
	//top 10 book in transaction
	@RequestMapping(value = "/admin/top-book-transaction", method=RequestMethod.GET)
	public String topBookTransaction(Model model){
		//get role
		SecurityContext context = SecurityContextHolder.getContext();
		String username = context.getAuthentication().getName();
		Object user = context.getAuthentication().getPrincipal();
		String role = StringUtils.EMPTY;
		if(user instanceof User){
			User userDetail = (User)user;
			for (GrantedAuthority ga : userDetail.getAuthorities() ) {
				//TODO save to list with account has many role access
				role = ga.getAuthority();
			}
		}
		
		SearchResult<Book> result = manageBookService.getTop10BookOfTransaction(role, username);
		List<Book> listBook = result.getSearchResult();
		manageBookService.createNewBook(model, null);
		model.addAttribute("listBook", listBook);
		
		return "admin/top10-transaction-info";
	}
}
